package com.castle.fortress.admin.study.exam.service.impl;

import cn.hutool.core.util.StrUtil;

import com.castle.fortress.admin.study.exam.dto.StudyExamDto;
import com.castle.fortress.admin.study.exam.dto.StudyExamStatisticsDto;
import com.castle.fortress.admin.study.exam.dto.StudyMemberExamDto;
import com.castle.fortress.admin.study.exam.entity.StudyExamStatisticsEntity;
import com.castle.fortress.admin.study.exam.entity.StudyMemberExamEntity;
import com.castle.fortress.admin.study.exam.service.*;
import com.castle.fortress.admin.utils.BizCommonUtil;
import com.castle.fortress.common.enums.YesNoEnum;
import com.castle.fortress.common.utils.ConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.castle.fortress.admin.study.exam.entity.StudyExamStatisticsMemberEntity;
import com.castle.fortress.admin.study.exam.dto.StudyExamStatisticsMemberDto;
import com.castle.fortress.admin.study.exam.mapper.StudyExamStatisticsMemberMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.List;

/**
 * 会员考试记录表 服务实现类
 *
 * @author castle
 * @since 2023-02-16
 */
@Service
public class StudyExamStatisticsMemberServiceImpl extends ServiceImpl<StudyExamStatisticsMemberMapper, StudyExamStatisticsMemberEntity> implements StudyExamStatisticsMemberService {
    @Autowired
    private StudyExamService studyExamService;
    @Autowired
    private StudyMemberExamService studyMemberExamService;
    @Autowired
    private StudyExamStatisticsService studyExamStatisticsService;
    @Autowired
    private StudyMemberUnfinishExamService studyMemberUnfinishExamService;

    /**
    * 获取查询条件
    * @param studyExamStatisticsMemberDto
    * @return
    */
    public QueryWrapper<StudyExamStatisticsMemberEntity> getWrapper(StudyExamStatisticsMemberDto studyExamStatisticsMemberDto){
        QueryWrapper<StudyExamStatisticsMemberEntity> wrapper= new QueryWrapper();
        if(studyExamStatisticsMemberDto != null){
            StudyExamStatisticsMemberEntity studyExamStatisticsMemberEntity = ConvertUtil.transformObj(studyExamStatisticsMemberDto,StudyExamStatisticsMemberEntity.class);
            wrapper.eq(studyExamStatisticsMemberEntity.getId() != null,"id",studyExamStatisticsMemberEntity.getId());
            wrapper.eq(studyExamStatisticsMemberEntity.getMemberId() != null,"member_id",studyExamStatisticsMemberEntity.getMemberId());
            wrapper.eq(studyExamStatisticsMemberEntity.getExamId() != null,"exam_id",studyExamStatisticsMemberEntity.getExamId());
            wrapper.like(StrUtil.isNotEmpty(studyExamStatisticsMemberEntity.getExamName()),"exam_name",studyExamStatisticsMemberEntity.getExamName());
            wrapper.eq(studyExamStatisticsMemberEntity.getTimeConsuming() != null,"time_consuming",studyExamStatisticsMemberEntity.getTimeConsuming());
            wrapper.eq(studyExamStatisticsMemberEntity.getQuizTime() != null,"quiz_time",studyExamStatisticsMemberEntity.getQuizTime());
            wrapper.eq(studyExamStatisticsMemberEntity.getScore() != null,"score",studyExamStatisticsMemberEntity.getScore());
        }
        wrapper.orderByDesc("quiz_time");
        return wrapper;
    }


    @Override
    public IPage<StudyExamStatisticsMemberDto> pageStudyExamStatisticsMember(Page<StudyExamStatisticsMemberDto> page, StudyExamStatisticsMemberDto studyExamStatisticsMemberDto) {
        QueryWrapper<StudyExamStatisticsMemberEntity> wrapper = getWrapper(studyExamStatisticsMemberDto);
        Page<StudyExamStatisticsMemberEntity> pageEntity = new Page(page.getCurrent(), page.getSize());
        Page<StudyExamStatisticsMemberEntity> studyExamStatisticsMemberPage=baseMapper.selectPage(pageEntity,wrapper);
        Page<StudyExamStatisticsMemberDto> pageDto = new Page(studyExamStatisticsMemberPage.getCurrent(), studyExamStatisticsMemberPage.getSize(),studyExamStatisticsMemberPage.getTotal());
        pageDto.setRecords(ConvertUtil.transformObjList(studyExamStatisticsMemberPage.getRecords(),StudyExamStatisticsMemberDto.class));
        return pageDto;
    }


    @Override
    public List<StudyExamStatisticsMemberDto> listStudyExamStatisticsMember(StudyExamStatisticsMemberDto studyExamStatisticsMemberDto){
        List<StudyExamStatisticsMemberEntity> list = baseMapper.listStudyExamStatisticsMember(studyExamStatisticsMemberDto);
        return ConvertUtil.transformObjList(list,StudyExamStatisticsMemberDto.class);
    }

    @Override
    public StudyExamStatisticsMemberDto saveMemberExam(StudyExamStatisticsMemberDto memberDTO) {
        Integer totalScore=0;
        List<StudyMemberExamDto> memberExamDtos=memberDTO.getExamQuestionDTOList();
        for(StudyMemberExamDto memberExamDTO:memberExamDtos){
            if(memberExamDTO.getAnswer().equals(memberExamDTO.getChoiceAnswer())){
                totalScore+=memberExamDTO.getScore();
            }
        }
        memberDTO.setScore(totalScore);
        memberDTO.setQuizTime(new Date());
        StudyExamDto examDTO=studyExamService.getByIdExtends(memberDTO.getExamId());
        if(totalScore>= examDTO.getQualifiedScore()){
            memberDTO.setStatus(YesNoEnum.YES.getCode());
        }else{
            memberDTO.setStatus(YesNoEnum.NO.getCode());
        }
        memberDTO.setTotalScore(examDTO.getTotalScore()+"");
        StudyExamStatisticsMemberEntity memberEntity = ConvertUtil.transformObj(memberDTO,StudyExamStatisticsMemberEntity.class);
        save(memberEntity);
        memberDTO.setId(memberEntity.getId());
        for(int i=0;i<memberExamDtos.size();i++){
            memberExamDtos.get(i).setRecordId(memberEntity.getId());
            memberExamDtos.get(i).setMemberId(memberDTO.getMemberId());
            memberExamDtos.get(i).setSort(i+1);
            memberExamDtos.get(i).setId(null);
        }
        List<StudyMemberExamEntity> memberExamEntities= ConvertUtil.transformObjList(memberExamDtos,StudyMemberExamEntity.class);
        studyMemberExamService.saveBatch(memberExamEntities);
        StudyExamStatisticsDto statisticsDTO =studyExamStatisticsService.queryByMemberAndExam(memberDTO.getMemberId(),memberDTO.getExamId());
        //第一次考试
        if(statisticsDTO ==null){
            statisticsDTO=new StudyExamStatisticsDto();
            statisticsDTO.setExamId(memberDTO.getExamId());
            statisticsDTO.setMemberId(memberDTO.getMemberId());
            statisticsDTO.setRecordId(memberEntity.getId());
            statisticsDTO.setTimeConsuming(memberDTO.getTimeConsuming());
            statisticsDTO.setQuizTime(memberDTO.getQuizTime());
            statisticsDTO.setHighScore(totalScore);
            statisticsDTO.setExamNum(1);
            statisticsDTO.setStatus(memberDTO.getStatus());
            studyExamStatisticsService.save(ConvertUtil.transformObj(statisticsDTO, StudyExamStatisticsEntity.class));
        }else{
            if(statisticsDTO.getHighScore()<=totalScore){
                statisticsDTO.setTimeConsuming(memberDTO.getTimeConsuming());
                statisticsDTO.setQuizTime(memberDTO.getQuizTime());
                statisticsDTO.setHighScore(totalScore);
                statisticsDTO.setRecordId(memberEntity.getId());
            }
            //判断是否合格
            if((totalScore>= examDTO.getQualifiedScore())){
                statisticsDTO.setStatus(YesNoEnum.YES.getCode());
            }
            statisticsDTO.setExamNum(statisticsDTO.getExamNum()+1);
            studyExamStatisticsService.updateById(ConvertUtil.transformObj(statisticsDTO, StudyExamStatisticsEntity.class));
        }
        studyMemberUnfinishExamService.deleteExam(memberDTO.getExamId(),memberDTO.getMemberId());
        return memberDTO;


    }

    @Override
    public StudyExamStatisticsMemberDto queryStatisticeMemberDetail(Long id) {
        StudyExamStatisticsMemberEntity entity = baseMapper.queryStatisticeMemberDetail(id);
        return ConvertUtil.transformObj(entity,StudyExamStatisticsMemberDto.class);
    }

    @Override
    public StudyExamStatisticsMemberDto queryStatisticeMemberInfo(Long id) {
        StudyExamStatisticsMemberEntity memberEntity = baseMapper.queryStatisticeMemberInfo(id);
        StudyExamStatisticsMemberDto memberDTO=ConvertUtil.transformObj(memberEntity,StudyExamStatisticsMemberDto.class);
        if(YesNoEnum.YES.getCode() == memberEntity.getIsLimited()  && memberEntity.getExamNum() >= memberEntity.getExamDesignNum()){
            memberDTO.setAllowAgain(false);
        }else{
            memberDTO.setAllowAgain(true);
        }
        if(YesNoEnum.YES.getCode() == memberEntity.getShowAnswerTime()){
            memberDTO.setShowAnswer(true);
        }else{
            memberDTO.setShowAnswer(false);
        }
        return memberDTO;
    }

    @Override
    public IPage<StudyExamStatisticsMemberDto> pageStudyExamStatisticsMemberExtends(Page<StudyExamStatisticsMemberDto> page, StudyExamStatisticsMemberDto dto) {
        Map<String,Long> pageMap = BizCommonUtil.getPageParam(page);
        StudyExamStatisticsMemberEntity entity = ConvertUtil.transformObj(dto,StudyExamStatisticsMemberEntity.class);
        List<StudyExamStatisticsMemberEntity> studyExamList=baseMapper.extendsList(pageMap,entity);
        Long total = baseMapper.extendsCount(entity);
        Page<StudyExamStatisticsMemberDto> pageDto = new Page(page.getCurrent(), page.getSize(),total);
        pageDto.setRecords(ConvertUtil.transformObjList(studyExamList,StudyExamStatisticsMemberDto.class));
        return pageDto;
    }
}

